/**
 * 功能描述
 *
 * @author: yekongyu
 * @date: 2023年01月10日 9:21
 */
package com.jiansu.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

public class DocumentUtil {

    /**
     * 从pdf中获取图片（已转成base64字符串）
     * @param path
     * @return
     */
    public static List<String> getPictureFromPdf(String path){
        try {
            return getPictureFromPdf(new FileInputStream(path));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static List<String> getPictureFromPdf(InputStream is){
        List<String> images=new ArrayList<>();
        try {
            PDDocument pdf= PDDocument.load(is);
            PDFRenderer renderer = new PDFRenderer(pdf);
            int pages = pdf.getNumberOfPages();
            for (int i = 0; i < pages; i++) {
                BufferedImage image = renderer.renderImage(i);
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                ImageIO.write(image, "png", stream);
                stream.flush();
                byte[] imageInByte = stream.toByteArray();
                stream.close();
                images.add(Base64.getEncoder().encodeToString(imageInByte));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return images;
    }
}
